import websocket
import json
import ssl
import time
import threading

def on_error(ws, error):
    print("Error:", error)

def on_close(ws, close_status_code, close_msg):
    print("Connection closed:", close_status_code, close_msg)
    print("正在重新连接")

def on_open(ws,okx_token_array):
    print("okx websocket open")
    # if ws.sock and ws.sock.connected:
    #     for token in okx_token_array:
    #         subscription_message = {
    #             "op":"subscribe",
    #             "args":[
    #                 {"channel":"books-grouped","instId":token,"grouping":"1"}
    #             ]
    #         }
    #         ws.send(json.dumps(subscription_message))
    #         print(token)
    # else:
    #     print("okx task 断开连接")


def send_message_periodically(ws, interval,okx_token_array=["BTC-USDT-SWAP-0.1"]):
    # token_array=[]
    # for token in okx_token_array:
    #     token_array.append({"channel":"books-grouped","instId":token,"grouping":"1"})
    
    # unsubscription_message={
    #     "op":"unsubscribe",
    #     "args":token_array
    # }
    while True:
        time.sleep(1)
        if ws.sock and ws.sock.connected:
            for token in okx_token_array:
                parts = token.rsplit('-', 1)
                instId = parts[0]  # "BTC-USDT-SWAP"
                grouping = parts[1]  # "0.1"
                subscription_message = {
                    "op":"subscribe",
                    "args":[
                        {"channel":"books-grouped","instId":instId,"grouping":grouping}
                    ]
                }
                ws.send(json.dumps(subscription_message))
                time.sleep(0.5)
        else:
            print("okx task 断开连接")
            break
        time.sleep(2)
        #ws.send(json.dumps(unsubscription_message))
        time.sleep(interval-3)
        


def send_ping(ws,interval):
    while True:
        time.sleep(interval)
        if ws.sock and ws.sock.connected:
            ws.send("ping")
        else:
            print("okx task 断开连接")
            break

def start_okx_websocket(callback,okx_token_array=["BTC-USDT-SWAP"]):
    websocket_url = "wss://wspri.okx.com:8443/ws/v5/ipublic"
    # 创建WebSocket应用程序对象
    ws = websocket.WebSocketApp(websocket_url,
                                on_open=lambda ws: on_open(ws,okx_token_array=okx_token_array),
                                on_message=lambda ws,message: callback(ws=ws,message=message),
                                on_error=on_error,
                                on_close=on_close
                                )

    # 运行WebSocket客户端
    # ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

    ws_thread = threading.Thread(target=ws.run_forever,kwargs={"sslopt": {"cert_reqs": ssl.CERT_NONE}})
    ws_thread.start()

    send_thread = threading.Thread(target=send_message_periodically, args=(ws, 30,okx_token_array))
    send_thread.start()

    send_ping_thread = threading.Thread(target=send_ping, args=(ws, 20))
    send_ping_thread.start()